package com.example.testapp.activity.activity.study;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.SuperActivity;
import com.example.testapp.activity.http.AsyncHttpUtil;
import com.example.testapp.activity.http.Contacts;
import com.example.testapp.activity.model.BlogItem;
import com.example.testapp.activity.ui.SuperUI;
import com.example.testapp.activity.view.ErrorHintView;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by l on 2016/10/10.
 */

public class BlogDetailActivity extends SuperActivity implements View.OnClickListener {

    private ErrorHintView  mHintView;
    private TextView  mTitle;
    private WebView   mWebView;

    public static int VIEW = 1;
    /**显示断网**/
    public static int VIEW_WIFIFAILUER = 2;
    /** 显示加载数据失败 **/
    public static int VIEW_LOADFAILURE = 3;
    public static int VIEW_LOADING = 4;

    private BlogItem item;
    private String url;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_news_blog_detail);
        getWindow().setBackgroundDrawable(null);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = this.getIntent();
        item = (BlogItem) intent.getSerializableExtra("item");
        if (item != null){
             mTitle.setText(item.getTitle());
            url = Contacts.PATH + item.getId();
            loadBolgDetailInfo(url);
        }
    }

    private void initView() {
        RelativeLayout  headView = (RelativeLayout) this.findViewById(R.id.head);
        RelativeLayout  leftBack = (RelativeLayout) this.findViewById(R.id.back_left);
        mTitle = (TextView) headView.findViewById(R.id.head_title);
        mWebView = (WebView) this.findViewById(R.id.webview);
        mHintView = (ErrorHintView) this.findViewById(R.id.hintView);
        LinearLayout top = (LinearLayout) this.findViewById(R.id.toolbar_top);
        LinearLayout comment = (LinearLayout) this.findViewById(R.id.toolbar_comment);
        LinearLayout save = (LinearLayout) this.findViewById(R.id.toolbar_save);
        leftBack.setOnClickListener(this);
        top.setOnClickListener(this);
        comment.setOnClickListener(this);
        save.setOnClickListener(this);
        ImageView saveImage = (ImageView) this.findViewById(R.id.save_image);
        TextView saveText = (TextView) this.findViewById(R.id.save_text);
        saveImage.setImageResource(R.mipmap.toolbar_favorite);
        saveText.setText("收藏");

        Intent intent = getIntent();
        item = (BlogItem) intent.getSerializableExtra("item");
        if (item != null){
            mTitle.setText(item.getTitle());
            url = Contacts.PATH + item.getId();
            showLoading(VIEW_LOADING);
            loadBolgDetailInfo(url);
        }
    }

    /**
     * 显示动态加载界面
     *
     * @param i
     */
    private void showLoading(int i) {
        mHintView.setVisibility(View.GONE);
        mWebView.setVisibility(View.GONE);

        switch (i){
            case 1:
                mHintView.hideLoading();
                mWebView.setVisibility(View.VISIBLE);
                break;
            case 2:
                mHintView.hideLoading();
                mHintView.netError(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                       showLoading(VIEW_LOADING);
                        loadBolgDetailInfo(url);
                    }
                });
                break;
            case 3:
                mHintView.hideLoading();
                mHintView.loadFailure(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                       showLoading(VIEW_LOADING);
                       loadBolgDetailInfo(url);
                    }
                });
                break;
            case 4:
                mHintView.loadingdata();
                break;
        }
    }

    /**
     * 加载详情内容
     * @param url
     */
    private void loadBolgDetailInfo(String url) {
        AsyncHttpUtil.get(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                 if (responseBody != null && responseBody.length > 0){
                     showLoading(VIEW);
                     ByteArrayInputStream bis = new ByteArrayInputStream(responseBody);
                     String result = parseDetailContentXml(bis);
                     initWebView(result);
                 }else{
                     showLoading(VIEW_LOADFAILURE);
                 }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                showLoading(VIEW_WIFIFAILUER);
            }
        });
    }

    private String parseDetailContentXml(InputStream bis) {
        XmlPullParser parser = Xml.newPullParser();
        String result = null;
        try {
            parser.setInput(bis, "UTF-8");
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT){
                switch (event){
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if ("string".equals(parser.getName())){
                            result = parser.nextText();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                    case XmlPullParser.TEXT:
                        break;
                }
                event = parser.next();
            }
        }catch (XmlPullParserException e){
             e.printStackTrace();
        }catch (IOException e){
             e.printStackTrace();
        }
        return result;
    }

    private void initWebView(String result) {
       mWebView.getSettings().setJavaScriptEnabled(true);
       mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
       mWebView.requestFocus();
       mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
       mWebView.setHorizontalScrollBarEnabled(false);
       mWebView.setVerticalScrollBarEnabled(false);
       mWebView.loadDataWithBaseURL(null,result,Contacts.WEB,"UTF-8",null);
       mWebView.getSettings().setSupportZoom(true);
       mWebView.getSettings().setBuiltInZoomControls(false);
       mWebView.setWebChromeClient(new WebChromeClient());
       mWebView.setWebViewClient(new MyWebViewClient());
    }

    class MyWebViewClient extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!TextUtils.isEmpty(url)){
                Log.d("shouldOverrideUrlLoading", "onPageFinished");
                mWebView.loadUrl(url);
            }
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            String title = view.getTitle();
            if (TextUtils.isEmpty(title)){
                return;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d("onReceivedError", "onReceivedError");
        }
    }

    @Override
    protected void obtainInfo() {

    }

    @Override
    public void onClick(View v) {
       switch (v.getId()){
           case R.id.back_left:
               finish();
               break;
           case R.id.toolbar_top:
               mWebView.scrollTo(0,0);
               break;
           case R.id.toolbar_comment:
               Intent intent = new Intent(mContext, BlogsCommentActivity.class);
               intent.putExtra("id", item.getId());
               intent.putExtra("title", item.getTitle());
               startActivity(intent);
               break;
           case R.id.toolbar_save:
               List<Object> list = mUserController.getCollectionInfo();
               if (list == null){
                 list = new ArrayList<Object>();
                 list.add(item);
                 mUserController.saveCollectionInfo(list);
                   SuperUI.showUncollectionUI(mContext);
               }else{
                  list.add(item);
                   mUserController.saveCollectionInfo(list);
                   SuperUI.showCollectionUI(mContext);
               }
               break;
           default:
               break;
       }
    }
}
